package com.etong.citymap.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.etong.citymap.bean.AssignmentBean;
import com.etong.citymap.bean.ImageBean;
import com.etong.citymap.bean.ViewHolder;
import com.etong.citymap.connect.HttpSendData;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.util.ImageLoader;
import com.etong.citymap.util.Status;
import com.etong.citymap.util.StringUtil;
import com.etong.citymap.util.log.LogUtil;

/**
 * 执法通任务列表
 */
public class LawEnforcementActivity extends Activity implements
		OnClickListener, OnItemClickListener, OnScrollListener {
	ListView listView;
	AlertDialog load;
	LinearLayout law_back;
	LinearLayout law_refresh;
	String path = "";
	private int pageindex;
	private int recordCount;
	private int getLastVisiblePosition;
	private int lastVisiblePositionY;
	private NotificationManager notificationManager;
	private static ArrayList<AssignmentBean> assignmentBeans = new ArrayList<AssignmentBean>();
	private ImageLoader mImageLoader = new ImageLoader(this);
	private CityApplication cityApplication;
	Handler handler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 2) {
				load.dismiss();
				String result = msg.getData().getString("result");
				if (result.equals("-2")) {
					Toast.makeText(LawEnforcementActivity.this, "没有新任务",
							Toast.LENGTH_SHORT).show();
					listView.setAdapter(baseAdapter);
				} else if (result.equals("-1")) {
					Toast.makeText(LawEnforcementActivity.this, "数据库异常",
							Toast.LENGTH_SHORT).show();
				} else if (result.equals("-3")) {
					Toast.makeText(LawEnforcementActivity.this, "未知错误，获取失败",
							Toast.LENGTH_SHORT).show();
				} else if (result.equals("-4")) {
					Toast.makeText(LawEnforcementActivity.this, "已在其他机器登录",
							Toast.LENGTH_SHORT).show();
				}else if (result.equals("-7")) {
					Toast.makeText(LawEnforcementActivity.this, "数据解析异常",
							Toast.LENGTH_SHORT).show();
				}
			} else if (msg.what == 3) {
				listView.setAdapter(baseAdapter);
				load.dismiss();
			}

			return false;
		}
	});

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		cityApplication = (CityApplication)getApplication();
		 path = Environment.getExternalStorageDirectory()	+ cityApplication.CameraPath;
		setContentView(R.layout.law);
		load = new ProgressDialog(this);
		load.setTitle(null);
		load.setCanceledOnTouchOutside(false);
		load.setMessage("请稍等,正在加载数据...");
		init();
		tongzhilan();
	}

	@SuppressWarnings({ "deprecation" })
	void tongzhilan() {// 通知栏
		String ns = Context.NOTIFICATION_SERVICE;
		String notificationtitle = "处置通";
		long when = System.currentTimeMillis();
		Integer icon = R.drawable.icon;
		if (notificationManager == null) {
			notificationManager = (NotificationManager) this
					.getSystemService(ns);
		}
		Notification notification = new Notification(icon, notificationtitle,
				when);
		notification.flags = Notification.FLAG_ONGOING_EVENT;
		CharSequence contentTitle = "处置通提示语";
		CharSequence contentText = "点击后从新返回到页面";
		Intent notificationIntent = new Intent(this,
				LawEnforcementActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);
		RemoteViews views = new RemoteViews(this.getPackageName(),
				R.layout.notificationlayout);
		views.setImageViewResource(R.id.n_icon, R.drawable.icon);
		views.setTextViewText(R.id.n_title, contentTitle);
		views.setTextViewText(R.id.n_content, contentText);
		notification.contentIntent = contentIntent;
		notification.contentView = views;
		notificationManager.notify(1, notification);
	}

	@Override
	protected void onResume() {
		pageindex = 0;
		assignmentBeans.clear();
		loading();

		if (cityApplication.getImageList() != null) {
			for (int i = 0; i < cityApplication.getImageList().length; i++) {
				File file = new File(path + "/" + cityApplication.getImageList()[i].getPathname());
				if (file.exists()) {
					file.delete();
				}
			}
			cityApplication.setImageList(null);
		}
		super.onResume();
	}

	void loading() {
		load.show();
		new Loading();
	}

	void init() {
		listView = (ListView) findViewById(R.id.lawalist);
		law_back = (LinearLayout) findViewById(R.id.law_back);
		law_back.setOnClickListener(this);
		listView.setOnItemClickListener(this);
		law_refresh = (LinearLayout) findViewById(R.id.law_refresh);
		law_refresh.setOnClickListener(this);
		listView.setOnScrollListener(this);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return true;
		}

		return super.onKeyUp(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		if (law_back == v) {
			exit();
		}
		if (law_refresh == v) {
			pageindex = 0;
			assignmentBeans.clear();
			loading();
		}
	}

	private void exit() {
		Builder builder = new Builder(LawEnforcementActivity.this);
		builder.setTitle("提示");
		builder.setMessage("你确定要退出程序?");
		builder.setPositiveButton("取消", null);
		builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				notificationManager.cancel(1); // 关闭通知栏
				//finish();
//				System.exit(0);
			}
		});
		builder.show();
	}

	class Loading extends Thread {
		public Loading() {
			start();
		}

		@Override
		public void run() {
			String url = "supervisor/ashx/czwaitnew.ashx"; // 001 001
			Map<String, String> map = new HashMap<String, String>();
			map.put("userid", cityApplication.getZFTUserId());
			map.put("orgid", cityApplication.getZFTOrgId());
			map.put("pageindex", pageindex + "");
			map.put("pagecount", cityApplication.PageCount + "");
			try {
				String result = HttpSendData.SendGet(url, map, "utf-8",cityApplication.getHTTPURL());
				if (result.equals("-1") || result.equals("-2")
						|| result.equals("-3") || result.equals("-4")) {
					Message message = new Message();
					message.getData().putString("result", result);
					message.what = 2;
					handler.sendMessage(message);
				} else {
					JSONArray jsonArray = new JSONArray(result);
					for (int i = 0; i < jsonArray.length(); i++) {
						AssignmentBean assignmentBean = new AssignmentBean();
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						assignmentBean.setPrjid(jsonObject.getString("prjid"));
						assignmentBean.setType(jsonObject.getString("type"));
						recordCount = jsonObject.getInt("recordCount");
						assignmentBean.setBigclass(jsonObject
								.getString("bigclass"));
						assignmentBean.setSmallclass(jsonObject
								.getString("smallclass"));
						assignmentBean.setSituation(jsonObject
								.getString("situation"));
						assignmentBean.setX(jsonObject.getString("x"));
						assignmentBean.setY(jsonObject.getString("y"));
						JSONArray pt1 = jsonObject.getJSONArray("photos1");
						JSONArray pt2 = jsonObject.getJSONArray("photos2");
						JSONArray pt3 = jsonObject.getJSONArray("photos3");
						assignmentBean.setActinsid(jsonObject
								.getString("actinsid"));
						assignmentBean.setAssignid(jsonObject
								.getString("assignid"));
						assignmentBean.setInsid(jsonObject.getString("insid"));
						assignmentBean.setWfid(jsonObject.getString("wfid"));
						assignmentBean.setTheoryenddate(jsonObject
								.getString("theoryenddate"));
						assignmentBean.setStatus(jsonObject.getInt("status"));
						assignmentBean.setStatusname(jsonObject
								.getString("statusname"));
						assignmentBean.setPrjname(jsonObject
								.getString("prjname"));
						assignmentBean.setPosition(jsonObject
								.getString("position"));
						String[] ptv1 = new String[pt1.length()];
						String[] ptv2 = new String[pt2.length()];
						String[] ptv3 = new String[pt3.length()];
						for (int t = 0; t < pt1.length(); t++) {
							ptv1[t] = pt1.getString(t);
						}
						for (int t = 0; t < pt2.length(); t++) {
							ptv2[t] = pt2.getString(t);
						}
						for (int t = 0; t < pt3.length(); t++) {
							ptv3[t] = pt3.getString(t);
						}
						assignmentBean.setPhoto1(ptv1);
						assignmentBean.setPhoto2(ptv2);
						assignmentBean.setPhoto3(ptv3);
						assignmentBeans.add(assignmentBean);
					}

					Message message = new Message();
					message.what = 3;
					handler.sendMessage(message);
				}
			} catch (Exception e) {
				Message message = new Message();
				message.what = 3;
				message.getData().putString("result", "-7");
				handler.sendMessage(message);
				LogUtil.e(e);
			}
		}
	}

	private BaseAdapter baseAdapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {

			ViewHolder vHolder;
			if (convertView == null) {
				convertView = LayoutInflater.from(LawEnforcementActivity.this)
						.inflate(R.layout.listitem, null);
				ImageView icon = (ImageView) convertView
						.findViewById(R.id.listitem_icon);
				ImageView icon_top = (ImageView) convertView
						.findViewById(R.id.listitem_icon_top);
				TextView title = (TextView) convertView
						.findViewById(R.id.listitem_title);
				TextView date = (TextView) convertView
						.findViewById(R.id.listitem_date);
				TextView content = (TextView) convertView
						.findViewById(R.id.listitem_content);
				vHolder = new ViewHolder();
				vHolder.setContent(content);
				vHolder.setDate(date);
				vHolder.setTitle(title);
				vHolder.setIcon(icon);
				convertView.setTag(vHolder);
			} else {
				vHolder = (ViewHolder) convertView.getTag();
			}
			AssignmentBean notesBean = assignmentBeans.get(position);
			String imgUrl = "";
			try {
				imgUrl = notesBean.getPhoto1()[0];
			} catch (Exception e) {
			}
			vHolder.getTitle().setText(notesBean.getPrjname());
			vHolder.getDate().setText("");
			vHolder.getContent().setText(notesBean.getSituation());

			try {
				if (StringUtil.IsNotNull(imgUrl)) {
					ImageView imageView = vHolder.getIcon();
					mImageLoader.DisplayImage(imgUrl, imageView, false);

				}
			} catch (Exception e) {
				LogUtil.e(e);
			}

			return convertView;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public int getCount() {
			return assignmentBeans.size();
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(1, 1, 1, "设置");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==1){
			Intent intent = new Intent(this, SettingActivity.class);
			startActivity(intent);

		}
		
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) { // 13274347520
		if (listView == parent) {
			cityApplication.setImageList(null);
			AssignmentBean bean = assignmentBeans.get(position);
			String[] t1 = bean.getPhoto1();
			String[] t2 = bean.getPhoto2();
			String[] t3 = bean.getPhoto3();
			ImageBean[] ibs= new ImageBean[t1.length + t2.length+ t3.length];
			int postion = 0;
			for (int i = 0; i < t1.length; i++) {
				ibs[postion] = new ImageBean();
				ibs[postion].setIsSelect(true);
				ibs[i].setUrlpath(t1[i]);
				String name = t1[i].substring(t1[i].lastIndexOf("/") + 1,t1[i].length());
				ibs[postion].setPathname(name);
				ibs[postion].setType(Status.ProjectType_SB);
				postion++;
			}

			for (int i = 0; i < t2.length; i++) {
				ibs[postion] = new ImageBean();
				ibs[postion].setIsSelect(true);
				ibs[postion].setUrlpath(t2[i]);
				String name = t2[i].substring(t2[i].lastIndexOf("/") + 1,
						t2[i].length());
				ibs[postion].setType(Status.ProjectType_HC);
				ibs[postion].setPathname(name);
				postion++;
			}

			for (int i = 0; i < t3.length; i++) {
				ibs[postion] = new ImageBean();
				ibs[postion].setIsSelect(true);
				ibs[postion].setUrlpath(t3[i]);
				String name = t3[i].substring(t3[i].lastIndexOf("/") + 1,
						t3[i].length());
				ibs[postion].setPathname(name);
				ibs[postion].setPathname(name);
				postion++;
			}
			cityApplication.setImageList_Net(ibs);
			Intent intent = new Intent(this, LawUploadActivity.class);
			intent.putExtra("bean", bean);
			startActivity(intent);
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (view == listView) {
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
					View v = (View) view.getChildAt(view.getChildCount() - 1);
					int[] location = new int[2];
					v.getLocationOnScreen(location);
					int y = location[1];
					if (view.getLastVisiblePosition() != getLastVisiblePosition
							&& lastVisiblePositionY != y) {
						getLastVisiblePosition = view.getLastVisiblePosition();
						lastVisiblePositionY = y;
						return;
					} else if (view.getLastVisiblePosition() == getLastVisiblePosition
							&& lastVisiblePositionY == y)// 第二次拖至底部
					{
						if (recordCount > assignmentBeans.size()) {
							pageindex++;
							loading();
						} else {
							Toast.makeText(LawEnforcementActivity.this,
									"已经没有可以加载的数据了", Toast.LENGTH_SHORT).show();
						}
					}
				}

				getLastVisiblePosition = 0;
				lastVisiblePositionY = 0;
			}
		}

	}
}
